package cn.ruanyun.backInterface.modules.business.profitPercent.serviceimpl;

import cn.ruanyun.backInterface.common.enums.ProfitTypeEnum;
import cn.ruanyun.backInterface.common.utils.*;
import cn.ruanyun.backInterface.common.vo.PageVo;
import cn.ruanyun.backInterface.common.vo.Result;
import cn.ruanyun.backInterface.modules.base.pojo.DataVo;
import cn.ruanyun.backInterface.modules.business.goodCategory.service.IGoodCategoryService;
import cn.ruanyun.backInterface.modules.business.profitPercent.mapper.ProfitPercentMapper;
import cn.ruanyun.backInterface.modules.business.profitPercent.pojo.ProfitPercent;
import cn.ruanyun.backInterface.modules.business.profitPercent.service.IProfitPercentService;
import cn.ruanyun.backInterface.modules.business.profitPercent.vo.ProfitPercentDetailVo;
import cn.ruanyun.backInterface.modules.business.profitPercent.vo.ProfitPercentVo;
import cn.ruanyun.backInterface.modules.business.userRelationship.service.IUserRelationshipService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jdk.nashorn.internal.runtime.options.Option;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;


/**
 * 分红比例接口实现
 * @author z
 */
@Slf4j
@Service
@Transactional
public class IProfitPercentServiceImpl extends ServiceImpl<ProfitPercentMapper, ProfitPercent> implements IProfitPercentService {

    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private IGoodCategoryService goodCategoryService;

    @Autowired
    private IUserRelationshipService userRelationshipService;

    @Override
    public void insertOrderUpdateProfitPercent(ProfitPercent profitPercent) {




        if (ToolUtil.isEmpty(profitPercent.getCreateBy())) {

            profitPercent.setCreateBy(securityUtil.getCurrUser().getId());
        }else {

            profitPercent.setUpdateBy(securityUtil.getCurrUser().getId());
        }
        this.saveOrUpdate(profitPercent);
    }

    @Override
    public void removeProfitPercent(String ids) {

        CompletableFuture.runAsync(() -> this.removeByIds(ToolUtil.splitterStr(ids))).join();
    }

    @Override
    public Result<DataVo<ProfitPercentVo>> getProfitPercent(PageVo pageVo, String categoryId) {

        //1. 获取分页基础数据
        Page<ProfitPercent> profitPercentPage = this.page(PageUtil.initMpPage(pageVo), Wrappers.<ProfitPercent>lambdaQuery()
                .eq(ToolUtil.isNotEmpty(categoryId), ProfitPercent::getCategoryId, categoryId)
                .orderByDesc(ProfitPercent::getCreateTime));

        //2. 获取封装数据
        if (ToolUtil.isEmpty(profitPercentPage.getRecords())) {

            return new ResultUtil<DataVo<ProfitPercentVo>>().setErrorMsg(201, "暂无数据！");
        }

        DataVo<ProfitPercentVo> result = new DataVo<>();

        result.setDataResult(profitPercentPage.getRecords().parallelStream().flatMap(profitPercent -> {

            ProfitPercentVo profitPercentVo = new ProfitPercentVo();
            profitPercentVo.setCategoryName(goodCategoryService.getGoodCategoryName(profitPercent.getCategoryId()));

            ToolUtil.copyProperties(profitPercent, profitPercentVo);

            return Stream.of(profitPercentVo);
        }).collect(Collectors.toList())).setCurrentPageNum(profitPercentPage.getCurrent()).setTotalPage(profitPercentPage.getTotal())
                .setTotalSize(profitPercentPage.getSize());

        return new ResultUtil<DataVo<ProfitPercentVo>>().setData(result, "获取分佣数据成功！");


    }

    /**
     * 获取各个等级的人的分佣比例
     *
     * @param categoryId 行业id
     * @param userId     当前购买人id
     * @return 分佣详情
     */
    @Override
    public ProfitPercentDetailVo getProfitPercentDetailVo(String categoryId, String userId) {

        //1. 或者当前行业的佣金比例
       return Optional.ofNullable(this.getOne(Wrappers.<ProfitPercent>lambdaQuery()
        .eq(ProfitPercent::getCategoryId, categoryId)
        .orderByDesc(ProfitPercent::getCreateTime)
        .last("limit 1")))
        .map(profitPercent -> {

            ProfitPercentDetailVo profitPercentDetailVo = new ProfitPercentDetailVo();

            //1.1 商家分润
            profitPercentDetailVo.setStorePercent(profitPercent.getStoreProfit());

            profitPercentDetailVo.setPlatformPercent(new BigDecimal("0.92").subtract(profitPercentDetailVo.getStorePercent()));

            //2. 判断当前用户有没有上级推荐人
            if (ToolUtil.isEmpty(userRelationshipService.getRelationUser(userId))) {

                profitPercentDetailVo.setPlatformPercent(new BigDecimal("0.94").subtract(profitPercentDetailVo.getStorePercent()))
                        .setPresenterPercent(new BigDecimal(0));
            }

            return profitPercentDetailVo;
        }).orElse(null);
    }
}